package com.xfcy.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xfcy.blog.common.R;
import com.xfcy.blog.common.constant.SqlConstant;
import com.xfcy.blog.common.enums.FriendLinkEnum;
import com.xfcy.blog.dto.FriendLinkDTO;
import com.xfcy.blog.mapper.FriendLinkMapper;
import com.xfcy.blog.entity.FriendLink;
import com.xfcy.blog.service.EmailService;
import com.xfcy.blog.service.FriendLinkService;
import com.xfcy.blog.utils.BeanCopyUtil;
import com.xfcy.blog.vo.FriendLinkVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.List;

import static com.xfcy.blog.common.constant.Constant.ZERO;

/**
 * 友情链接表(FriendLink)表服务实现类
 *
 * @author 晓风残月Lx
 * @since 2023-04-09 11:03:05
 */
@Service("friendLinkService")
public class FriendLinkServiceImpl extends ServiceImpl<FriendLinkMapper, FriendLink> implements FriendLinkService {

    @Resource
    private EmailService emailService;


    /**
     * 友链列表
     * @param pageNo
     * @param pageSize
     * @param name
     * @param status
     * @return
     */
    @Override
    public R listFriendLink(Integer pageNo, Integer pageSize, String name, Integer status) {
        QueryWrapper<FriendLink> queryWrapper = new QueryWrapper<FriendLink>()
                .orderByDesc(SqlConstant.SORT)
                .like(StringUtils.isNotBlank(name), SqlConstant.NAME, name)
                .eq(status != null, SqlConstant.STATUS, status);
        Page<FriendLink> friendLinkPage = baseMapper.selectPage(new Page<>(pageNo, pageSize), queryWrapper);
        return R.success(friendLinkPage);
    }

    /**
     * 添加友链
     * @param friendLinkDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addFriendLink(FriendLinkDTO friendLinkDTO) {
        FriendLink friendLink = BeanCopyUtil.copyObject(friendLinkDTO, FriendLink.class);
        int insert = baseMapper.insert(friendLink);
        return insert > 0 ? R.success() : R.error();
    }

    /**
     * 修改友链
     * @param friendLinkDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updateFriendLink(FriendLinkDTO friendLinkDTO) {
        if (friendLinkDTO.getStatus().equals(ZERO)) {
            Assert.isTrue(true, "下架原因不能为空");
        }
        FriendLink friendLink = BeanCopyUtil.copyObject(friendLinkDTO, FriendLink.class);
        // 判断是否已经更改网站状态
        if(!isChangeStatus(friendLinkDTO)) {
            //审核通过和未通过发送邮件通知
            baseMapper.updateById(friendLink);
            emailService.sendFriendEmail(friendLink);
        } else {
            baseMapper.updateById(friendLink);
        }
        return R.success();
    }

    /**
     * 删除友链
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deleteFriendLink(List<Long> ids) {
        baseMapper.deleteBatchIds(ids);
        return R.success();
    }


    // Web方法 =====================================

    /**
     * 查询所有友链
     * @return
     */
    @Override
    public R webFriendLinkList() {
        List<FriendLinkVO> friendLinkVOS = baseMapper.selectLinkList(FriendLinkEnum.UP.getCode());
        return R.success(friendLinkVOS);
    }

    /**
     * 添加友链
     * @param friendLinkDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R applyFriendLink(FriendLinkDTO friendLinkDTO) {
        Assert.isTrue(!friendLinkDTO.getUrl().contains("xfcylx.top") &&
                !friendLinkDTO.getUrl().contains("baidu.com"), "不合法的网址！");

        FriendLink friendLink = BeanCopyUtil.copyObject(friendLinkDTO, FriendLink.class);

        // 如果已经申请过友链，再次接入则会进行下架处理，需要重新审核
        FriendLink entity = baseMapper.selectOne(new QueryWrapper<FriendLink>()
                .eq(SqlConstant.URL, friendLinkDTO.getUrl()));
        if (entity != null) {
            friendLink.setId(entity.getId());
            baseMapper.updateById(friendLink);
        } else {
            baseMapper.insert(friendLink);
        }

        // 异步操作邮箱发送
        emailService.emailNoticeMe("【你的博客】友链接入通知", "老大，网站有新的友链接入啦（" + friendLink.getUrl() +")，快去审核！！！");

        return R.success();
    }




    // 自定义方法

    /**
     * 判断是否更改状态
     * @param friendLink
     * @return
     */
    private boolean isChangeStatus(FriendLinkDTO friendLink) {
        FriendLink friend = baseMapper.selectOne(new QueryWrapper<FriendLink>().select(SqlConstant.STATUS).eq(SqlConstant.ID, friendLink.getId()));
        return friend.getStatus().equals(friendLink.getStatus());
    }

}


